package com.zut.hospital.service.pharmacy;

import com.alibaba.fastjson.JSON;
import com.zut.hospital.dao.diagnose.Mdc_Rec_RelationMapper;
import com.zut.hospital.dao.diagnose.PatientMapper;
import com.zut.hospital.dao.diagnose.RecordMapper;
import com.zut.hospital.dao.pharmacy.InventoryMapper;
import com.zut.hospital.dao.pharmacy.MedicineMapper;
import com.zut.hospital.dao.pharmacy.PurchaseMapper;
import com.zut.hospital.dao.pharmacy.Sale_RecordMapper;
import com.zut.hospital.dao.staff.UserMapper;
import com.zut.hospital.entity.diagnose.*;
import com.zut.hospital.entity.pharmacy.*;
import com.zut.hospital.entity.staff.User;
import com.zut.hospital.entity.staff.UserExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: hos-test
 * @description:
 * @author: 杨曼珍
 * @create: 2019-06-21 13:22
 **/
@Service
public class SaleRecordServiceImpl implements SaleRecordService {
    private static final Logger log = LoggerFactory.getLogger(SaleRecordServiceImpl.class);
    @Autowired
    Sale_RecordMapper sale_recordMapper;
    @Autowired
    PatientMapper patientMapper;
    @Autowired
    MedicineMapper medicineMapper;
    @Autowired
    Mdc_Rec_RelationMapper mdc_rec_relationMapper;
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    PurchaseMapper purchaseMapper;
    @Autowired
    InventoryMapper inventoryMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public String layuiJsonParse(List<Map<String, String>> list, int size) {
        Map<String, Object> layuiMap = new HashMap<>();
        layuiMap.put("code", 1);
        layuiMap.put("msg", "success");
        layuiMap.put("count", size);
        layuiMap.put("data", list);
        return JSON.toJSONString(layuiMap);
    }
//所有损坏药品
    @Override
    public String broken(){
        Map<String,String>map;
        List<Map<String,String>>resaultmap=new ArrayList<>();
        Sale_RecordExample sale_recordExample=new Sale_RecordExample();
        sale_recordExample.createCriteria().andSaleRecTypeEqualTo(2);
        List<Sale_Record> list=sale_recordMapper.selectByExample(sale_recordExample);
        for (Sale_Record sale_record:list){
            map=new HashMap<>();
            MedicineExample medicineExample=new MedicineExample();
            medicineExample.createCriteria().andIdEqualTo(sale_record.getSaleRecMdcId());
            Medicine medicine=medicineMapper.selectByExample(medicineExample).get(0);

            UserExample userExample=new UserExample();
            userExample.createCriteria().andIdEqualTo(sale_record.getSaleRecPhysician());
            User user=userMapper.selectByExample(userExample).get(0);

            map.put("name",medicine.getMdcName());
            map.put("count",sale_record.getSaleRecCount().toString());
            map.put("remark",sale_record.getSaleRecRemark());
            map.put("time",new SimpleDateFormat("yyyy-MM-dd").format(sale_record.getSaleRecTime()));
            map.put("user",user.getAdName());
            resaultmap.add(map);
        }

        Map<String, Object> layuiMap = new HashMap<>();
        layuiMap.put("code", 0);
        layuiMap.put("msg", "success");
        layuiMap.put("count", resaultmap.size());
        layuiMap.put("data", resaultmap);
        return JSON.toJSONString(layuiMap);
    }
    public Map selectAll(Mdc_Rec_Relation mdc_rec_relation){
        Map<String,String>map;

        MedicineExample medicineExample=new MedicineExample();
        medicineExample.createCriteria().andIdEqualTo(mdc_rec_relation.getRelatMdcId());
        Medicine medicine=medicineMapper.selectByExample(medicineExample).get(0);
        String mdc_name=medicine.getMdcName();

        RecordExample recordExample=new RecordExample();
        recordExample.createCriteria().andIdEqualTo(mdc_rec_relation.getRelatRecId());
        Record record=recordMapper.selectByExample(recordExample).get(0);

        PatientExample patientExample=new PatientExample();
        patientExample.createCriteria().andIdEqualTo(record.getRecPatId());
        Patient patient=patientMapper.selectByExample(patientExample).get(0);
        String pat_name=patient.getPatName();
        String time=new SimpleDateFormat("yyyy-MM-dd").format(patient.getPatCreateTime());


        map=new HashMap<>();
        map.put("time",time);
        map.put("pat_name",pat_name);
        map.put("mdc_name",mdc_name);
        map.put("count",mdc_rec_relation.getRelatMdcCount().toString());
        return map;

    }

    /*所有sale*/
    @Override
    public  String getAll(){

        List<Mdc_Rec_Relation>mdc_rec_relationList = mdc_rec_relationMapper.selectDesc();
        List<Map<String,String>>resaultmap=new ArrayList<>();
        for (Mdc_Rec_Relation mdc_rec_relation:mdc_rec_relationList){

            RecordExample recordExample=new RecordExample();
            recordExample.createCriteria().andIdEqualTo(mdc_rec_relation.getRelatRecId());
            Record record=recordMapper.selectByExample(recordExample).get(0);

            PatientExample patientExample=new PatientExample();
            patientExample.createCriteria().andIdEqualTo(record.getRecPatId());
            Patient patient=patientMapper.selectByExample(patientExample).get(0);
            if (patient.getPatStatus()==3) {
                resaultmap.add(selectAll(mdc_rec_relation));
            }
        }
            return layuiJsonParse(resaultmap.subList(0, 6),resaultmap.subList(0, 6).size());


    }
    //所有订单
    @Override
    public  String dingdan(){

        List<Mdc_Rec_Relation>mdc_rec_relationList = mdc_rec_relationMapper.selectDesc();
        List<Map<String,String>>resaultmap=new ArrayList<>();
        for (Mdc_Rec_Relation mdc_rec_relation:mdc_rec_relationList){

            RecordExample recordExample=new RecordExample();
            recordExample.createCriteria().andIdEqualTo(mdc_rec_relation.getRelatRecId());
            Record record=recordMapper.selectByExample(recordExample).get(0);

            PatientExample patientExample=new PatientExample();
            patientExample.createCriteria().andIdEqualTo(record.getRecPatId());
            Patient patient=patientMapper.selectByExample(patientExample).get(0);
            if (patient.getPatStatus()==3) {
                resaultmap.add(selectAll(mdc_rec_relation));
            }
        }
        Map<String, Object> layuiMap = new HashMap<>();
        layuiMap.put("code", 0);
        layuiMap.put("msg", "success");
        layuiMap.put("count", resaultmap.size());
        layuiMap.put("data", resaultmap);
        return JSON.toJSONString(layuiMap);


    }
//扇
    @Override
    public  String shan()throws ParseException {
        int size;
        int id[]=new int[20];
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
        Date nowTime = new Date();
        System.out.println(nowTime);
        String number=new SimpleDateFormat("yyyy-MM-dd").format(nowTime);
        List<Sale_Record>sale_recordList=sale_recordMapper.selectByTime(number);

        System.out.println("sale_recordList"+sale_recordList.toString());
        List<Map<String,String>>resaultmap=new ArrayList<>();

        int x=0;
        int my=0;
        for (Sale_Record sale_record:sale_recordList){
            int flag=0;
            int mdc_id=sale_record.getSaleRecMdcId();
            for (int j=0;j<id.length;j++){
                if (id[j]==mdc_id){
                    flag=1;
                    break;
                }
            }
            if (flag==1)
                continue;
            my++;

            System.out.println("my:"+my);
            Map<String,String>map=new HashMap<>();
            MedicineExample medicineExample=new MedicineExample();
            medicineExample.createCriteria().andIdEqualTo(mdc_id);
            Medicine medicine=medicineMapper.selectByExample(medicineExample).get(0);
            String mdc_name=medicine.getMdcName();
            log.info("med_name:"+mdc_name);
            System.out.println("med_name:"+mdc_name);
            int i=sale_record.getSaleRecCount();
            for (Sale_Record sale_record1:sale_recordList){
                if (sale_record1.getId()!=sale_record.getId()) {
                    if (sale_record1.getSaleRecMdcId() == mdc_id) {
                        id[x] = mdc_id;
                        i = i + sale_record1.getSaleRecCount();
                        System.out.println(i);
                    }
                }
            }

            map.put("name",mdc_name);
            map.put("count",String.valueOf(i));
            if (map.isEmpty()){
               continue;
            }
            resaultmap.add(map);
            x++;
        }

        log.info(resaultmap.toString());
        size=resaultmap.size();
        return layuiJsonParse(resaultmap,size);
    }
    //折线
    @Override
    public  String zhe(Date month)throws ParseException {
        String number=new SimpleDateFormat("yyyy-MM-dd").format(month);
        int today=Integer.parseInt(number.substring(number.length()-2));
        List<Map<String,String>>resaultmap=new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(month);//month 为指定月份任意日期
        int year = cal.get(Calendar.YEAR);
        int m = cal.get(Calendar.MONTH);
//        int dayNumOfMonth = getDaysByYearMonth(year, m);
        cal.set(Calendar.DAY_OF_MONTH, 1);// 从一号开始
        for (int i = 0; i < today; i++,cal.add(Calendar.DATE, 1)) {
            Date d = cal.getTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String df = simpleDateFormat.format(d);
            List<Sale_Record>sale_recordList=sale_recordMapper.selectByTime(df);

            Map<String,String>map=new HashMap<>();
            double a=0;
            for (Sale_Record sale_record:sale_recordList){
                if (sale_record.getSaleRecType()!=2)
                a=a+sale_record.getSaleRecTotal();
            }
            map.put("date",df.substring(df.length()-5));
            map.put("total",String.valueOf(a));
            resaultmap.add(map);
        }

        log.info(resaultmap.toString());
        return layuiJsonParse(resaultmap,resaultmap.size());
    }
    //快速出库
    @Override
    public  String saleelse(String name,String count,String remark,String yisheng,int type)throws ParseException{

        MedicineExample medicineExample = new MedicineExample();
        medicineExample.createCriteria().andMdcNameEqualTo(name);
        Medicine medicine = medicineMapper.selectByExample(medicineExample).get(0);

        Date nowTime = new Date();
        System.out.println(nowTime);
        String number = new SimpleDateFormat("yyyyMMddHHmmss").format(nowTime);

        UserExample userExample=new UserExample();
        userExample.createCriteria().andAdNameEqualTo(yisheng);
        User user=userMapper.selectByExample(userExample).get(0);

        Date date=new Date();
        System.out.println("date"+date);

        InventoryExample inventoryExample=new InventoryExample();
        inventoryExample.createCriteria().andIvtrMdcIdEqualTo(medicine.getId());
        Inventory inventory=inventoryMapper.selectByExample(inventoryExample).get(0);
        if (inventory.getIvtrCount()<Integer.parseInt(count)){
            Map<String, Object> layuiMap = new HashMap<>();
            layuiMap.put("code", 0);
            layuiMap.put("msg", "failed");
            layuiMap.put("count", 0);
            layuiMap.put("data", "");
            return JSON.toJSONString(layuiMap);
        }

        Sale_Record sale_record = new Sale_Record();
        sale_record.setSaleRecCount(Integer.parseInt(count));
        sale_record.setSaleRecMdcId(medicine.getId());
        sale_record.setSaleRecNumber(number);
        sale_record.setSaleRecPhysician(user.getId());
        sale_record.setSaleRecPrice(Double.parseDouble(medicine.getMdcRemark()));
        sale_record.setSaleRecTime(date);
        sale_record.setSaleRecTotal(Double.parseDouble(medicine.getMdcRemark()) * Integer.parseInt(count));
        sale_record.setSaleRecType(type);
        sale_record.setSaleRecRemark(remark);
        sale_recordMapper.insert(sale_record);

        InventoryExample inventoryExample1 = new InventoryExample();
        inventoryExample1.createCriteria().andIvtrMdcIdEqualTo(medicine.getId());
        Inventory inventory1 = inventoryMapper.selectByExample(inventoryExample1).get(0);
        inventory1.setIvtrCount(inventory1.getIvtrCount() - Integer.parseInt(count));
        inventoryMapper.updateByExample(inventory1, inventoryExample1);


        return layuiJsonParse(null,0);

    }
    //正常销售
    @Override
    public  String sale(String name,String count,String patname,String username)throws ParseException{
log.info(patname);
            MedicineExample medicineExample = new MedicineExample();
            medicineExample.createCriteria().andMdcNameEqualTo(name);
            Medicine medicine = medicineMapper.selectByExample(medicineExample).get(0);

            Date nowTime = new Date();
            System.out.println(nowTime);
            String number = new SimpleDateFormat("yyyyMMddHHmmss").format(nowTime);

        UserExample userExample=new UserExample();
        userExample.createCriteria().andAdNameEqualTo(username);
        User user=userMapper.selectByExample(userExample).get(0);

        InventoryExample inventoryExample1=new InventoryExample();
        inventoryExample1.createCriteria().andIvtrMdcIdEqualTo(medicine.getId());
        Inventory inventory1=inventoryMapper.selectByExample(inventoryExample1).get(0);
        if (inventory1.getIvtrCount()<Integer.parseInt(count)){
            Map<String, Object> layuiMap = new HashMap<>();
            layuiMap.put("code", 0);
            layuiMap.put("msg", "failed");
            layuiMap.put("count", 0);
            layuiMap.put("data", "");
            return JSON.toJSONString(layuiMap);
        }


        Sale_Record sale_record = new Sale_Record();
            sale_record.setSaleRecCount(Integer.parseInt(count));
            sale_record.setSaleRecMdcId(medicine.getId());
            sale_record.setSaleRecNumber(number);
            sale_record.setSaleRecPhysician(user.getId());
            sale_record.setSaleRecPrice(Double.parseDouble(medicine.getMdcRemark()));
            sale_record.setSaleRecTime(new Date());
            sale_record.setSaleRecTotal(Double.parseDouble(medicine.getMdcRemark()) * Integer.parseInt(count));
            sale_record.setSaleRecType(1);
            sale_record.setSaleRecRemark("");
            sale_recordMapper.insert(sale_record);

            InventoryExample inventoryExample = new InventoryExample();
            inventoryExample.createCriteria().andIvtrMdcIdEqualTo(medicine.getId());
            Inventory inventory = inventoryMapper.selectByExample(inventoryExample).get(0);
            inventory.setIvtrCount(inventory.getIvtrCount() - Integer.parseInt(count));
            inventoryMapper.updateByExample(inventory, inventoryExample);


            PatientExample patientExample = new PatientExample();
            patientExample.createCriteria().andPatNameEqualTo(patname);
            Patient patient = patientMapper.selectByExample(patientExample).get(0);
            patient.setPatStatus(3);
            patientMapper.updateByExample(patient,patientExample);

        return layuiJsonParse(null,0);

    }
}
